﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Configuration;

namespace Subsidiary.BookSearch
{
    public class BookItem
    {
        public Guid Id { get; set; }
        #region Constants and Fields

        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string author;
        public string Author
        {
            get { return author; }
            set { author = value; }
        }
        private string picture;
        public string Picture
        {
            get { return picture; }
            set { picture = value; }
        }
        private string publishing;
        public string Publishing
        {
            get { return publishing; }
            set { publishing = value; }
        }
        private string status;
        public string Status
        {
            get { return status; }
            set { status = value; }
        }
        private string summary;
        public string Summary
        {
            get { return summary; }
            set { summary = value; }
        }
        private string comment;
        public string Comment
        {
            get { return comment; }
            set { comment = value; }
        }

        #endregion

        public void InsertBook(BookItem book)
        {
            string folder = ConfigurationManager.AppSettings["DataFolder"];
            if (!Directory.Exists(string.Format("{0}books", folder)))
            {
                Directory.CreateDirectory(string.Format("{0}books", folder));
            }

            var fileName = string.Format("{0}books{1}{2}.xml", folder, Path.DirectorySeparatorChar, book.Id);
            var settings = new XmlWriterSettings { Indent = true };

            var ms = new MemoryStream();

            using (var writer = XmlWriter.Create(ms, settings))
            {
                writer.WriteStartDocument(true);


                writer.WriteStartElement("book");
                writer.WriteElementString("name", book.Name);
                writer.WriteElementString("author", book.Author);
                writer.WriteElementString("picture", book.Picture);
                writer.WriteElementString("publishing", book.Publishing);
                writer.WriteElementString("status", book.Status);
                writer.WriteElementString("summary", book.Summary);
                writer.WriteElementString("comment", book.Comment);
                writer.WriteEndElement();
            }

            using (var fs = File.Open(fileName, FileMode.Create, FileAccess.Write))
            {
                ms.WriteTo(fs);
                ms.Dispose();
            }
        }

    }
}
